/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.tiannianbao;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tiannianbao.util.HttpDownloadUtility;
import com.tiannianbao.util.ZipUtil;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class MainActivity extends CordovaActivity implements ProcessCallback {
    private static final String TAG = "MyActivity";

    public static final int MSG_SUCCESS = 0;//成功标识
    public static final int MSG_CLOSE_LOADPAGE = 1;//关闭加载页标识
    public static final int MSG_PROG_COMPAREVERSION = 11;//比较版本
    public static final int MSG_PROG_UPDATING = 12;//下载更新
    public static final int MSG_PROG_UPDATE_SUC = 13;//下载更新完毕
    public static final int MSG_PROG_UPDATE_UNZIP = 14;//解压
    public static final int MSG_PROG_GOPAGE = 15;//加载页面
    public static final int MSG_PROG_INPAGE = 16;//进入页面
    public static final int MSG_PROG_INSHOW = 21;//显示进度
    private String sysRoot = null;
    private String appRoot = null;//应用所属路径
    private String versionFilePath = null;
    private String noticeTag = null;
    private String language = null;
    private String serverUrl = null;

    private SystemWebView wv;
    private ProgressBar progressBar;
    private ProgressBar downloadProgressBar;
    private TextView tipText;
    private TextView downloadTipText;
    private Thread mThread;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //根据消息类型进行处理
            if (msg.what == MSG_PROG_GOPAGE) {
                //转向主页面
                goPage();
            }
            if (msg.what == MSG_CLOSE_LOADPAGE) {
                //关闭加载页
                closeLoadingPage();
            }
            if (msg.what == MSG_PROG_INSHOW) {
                JSONArray data = (JSONArray) msg.obj;
                try {
                    //判断为进度显示，则进行UI处理
                    if (data.getString(0).equals("main")) {
                        if (data.getString(1).equals("1")) {
                            //显示打开页面
                            tipText.setText("正在打开页面");
                            progressBar.setProgress(100);
                        }
                    }
                    if (data.getString(0).equals("download")) {
                        //显示下载进度
                        String per = data.getString(1);
                        downloadProgressBar.setProgress(Integer.parseInt(per));
                        downloadTipText.setText(Integer.parseInt(per) + "%");
                    }
                } catch (Exception e) {
                    Log.e(TAG, "progress show err", e);
                }
            }
            if (msg.what == MSG_PROG_COMPAREVERSION) {
                tipText.setText("正在比较版本");
                progressBar.setProgress(20);
            }
            if (msg.what == MSG_PROG_UPDATING) {
                tipText.setText("正在下载更新");
                downloadProgressBar.setVisibility(View.VISIBLE);
                downloadProgressBar.setProgress(0);
                downloadTipText.setVisibility(View.VISIBLE);
                progressBar.setProgress(30);
            }
            if (msg.what == MSG_PROG_UPDATE_UNZIP) {
                tipText.setText("更新下载完毕，正在解压");
                progressBar.setProgress(60);
                downloadProgressBar.setVisibility(View.GONE);
                downloadTipText.setVisibility(View.GONE);
            }
            if (msg.what == MSG_PROG_GOPAGE) {
                tipText.setText("正在加载页面");
                progressBar.setProgress(80);
            }
            if (msg.what == MSG_PROG_INPAGE) {
                tipText.setText("正在打开页面");
                progressBar.setProgress(100);
            }
            if (msg.what == MSG_PROG_GOPAGE) {
                //转向主页面
                goPage();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();
        int isFirstRun = isFirstRun();
        //初始化环境变量
        this.initEnvironment(isFirstRun);
        //加载进度页面
        setContentView(R.layout.layout);
        setProgressBarVisibility(true);
        setProgressBarIndeterminateVisibility(true);
        setProgress(3500);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        tipText = (TextView) findViewById(R.id.tipText);
        downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProcessBar);
        downloadTipText = (TextView) findViewById(R.id.downloadProcessText);
        //隐藏下载进度信息
        downloadProgressBar.setVisibility(View.GONE);
        downloadTipText.setVisibility(View.GONE);
        //后续需要进入子线程进行操作
        mThread = new Thread(innerProcessor);
        mThread.start();
    }

    public void closeLoadingPage() {
//        rectangle.setVisibility(View.GONE);
//        circle.setVisibility(View.GONE);
        this.setContentView(appView.getView());
    }

    //判断是否安装后第一次运行
    private int isFirstRun() {
        SharedPreferences setting = getSharedPreferences("flag.properties", 0);
        int notFirstRun = setting.getInt("not_first_run", 0);
        System.out.println("notFirstRun iss:" + notFirstRun);
        if (notFirstRun == 0) {// 第一次
            setting.edit().putInt("not_first_run", 1).commit();
            return 1;
        }
        return 0;
    }

    /*
     * 初始化环境变量
     */
    public void initEnvironment(int isFirstRun) {
        //初始化变量
        String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        System.out.println("this rootPath :" + rootPath);
        this.sysRoot = rootPath;
        //取得安装路径
        PackageManager m = getPackageManager();
        String s = getPackageName();
        try {
            PackageInfo p = m.getPackageInfo(s, 0);
            this.appRoot = p.applicationInfo.dataDir;
            System.out.println("this.appRoot:" + this.appRoot);
        } catch (PackageManager.NameNotFoundException e) {
            Log.w(TAG, "Error Package name not found ", e);
            return;
        }
        //第一次运行时创建目录
        if (isFirstRun == 1 || true) {
            this.directoryInit();
        }
    }

    /*
     * 初始化目录
     */
    public void directoryInit() {
        createDirectory(this.getAbsPath(Envir.GLOBALVAR_storeResource));
        createDirectory(this.getAbsPath(Envir.GLOBALVAR_storeAppResource));
        createDirectory(this.getAbsPath(Envir.GLOBALVAR_storeChatAudioFilePath));
    }

    /*
     * 比较版本并下载更新
     */
    public void compareVersion() {
        String localFilePath = this.getAbsPath(Envir.GLOBALVAR_storeAppResource + "/resource.json");
        String saveDir = this.getAbsPath(Envir.GLOBALVAR_storeRoot);
        String saveFile = saveDir + "/resource_remote.json";
        String versionFileUrl = Envir.GLOBALVAR_resourceUrl + "/resource.json?ver=" + Math.random();
        System.out.println("saveDir is:" + saveDir + " and versionFilePath:" + this.versionFilePath);
        try {
            //下载版本文件
            HttpDownloadUtility.downloadFile(versionFileUrl, saveDir, "resource_remote.json", null);
            //取得版本信息
            String remoteJsonContent = ZipUtil.getStringFromFile(saveFile);
            JSONObject rObject = new JSONObject(remoteJsonContent);
            Integer remoteVersion = rObject.getInt("version");
            Integer localVersion = 0;
            String localJsonContent = ZipUtil.getStringFromFile(localFilePath);
            if (localJsonContent != null) {
                JSONObject lObject = new JSONObject(localJsonContent);
                localVersion = lObject.getInt("version");
            }
            System.out.println("remoteVersion is:" + remoteVersion + " and localVersion:" + localVersion);

            //版本没有更新，不用下载
            if (remoteVersion.intValue() <= localVersion.intValue()) {
                System.out.println("no need update ver");
                return;
            }
            handler.obtainMessage(MSG_PROG_UPDATING).sendToTarget();
            //删除原目录
            ZipUtil.removeFolder(new File(this.getAbsPath(Envir.GLOBALVAR_storeAppResource)));
            createDirectory(this.getAbsPath(Envir.GLOBALVAR_storeAppResource));
            //下载
            this.wholeDownload();
            handler.obtainMessage(MSG_PROG_UPDATE_UNZIP).sendToTarget();
            String zipFile = this.getAbsPath(Envir.GLOBALVAR_storeAppResource + "/resource.zip");
            String targetPath = this.getAbsPath(Envir.GLOBALVAR_storeAppResource);
            //解压
            ZipUtil.unzip(this.getAbsPath(Envir.GLOBALVAR_storeAppResource), "resource.zip");
            //需要把远程文件变成本地版本文件
            File from = new File(saveFile);
            File to = new File(localFilePath);
            from.renameTo(to);
            System.out.println("unzip ok");
        } catch (Exception ex) {
            Log.e(TAG, "compareVersion fail", ex);
        }
    }

    /*
     * 下载更新包
     */
    public void wholeDownload() throws IOException {
        System.out.println("need download zip");
        String remoteUrl = Envir.GLOBALVAR_resourceUrl + "/resource.zip";
        String zipFilePath = this.getAbsPath(Envir.GLOBALVAR_storeAppResource);
        HttpDownloadUtility.downloadFile(remoteUrl, zipFilePath, "resource.zip", this);
    }

    private String getAbsPath(String relPath) {
//        return Environment.getExternalStorageDirectory().getPath() + File.separator + relPath;
        return this.appRoot + File.separator + relPath;
    }

    /*
     * 跳转到web页面
     */
    private void goPage() {
        //拼接页面本地链接
        String urlpath = "file://" + this.getAbsPath(Envir.GLOBALVAR_storeAppResource);
//        urlpath = "http://192.168.1.246:4200";
        String url = "file:///android_asset/www/index.html?ver=" + Calendar.getInstance().getTimeInMillis() + "&urlpath=" + urlpath + "&sdkver=" + Build.VERSION.SDK_INT;
        System.out.println("url end:" + url);
        loadUrl(url);
    }

    /*
     * 创建目录
     */
    public static void createDirectory(String path) {
        File f = new File(path);
        f.mkdirs();
    }


    public void progress(Integer per) {
        String template = "'detail',";
        JSONArray array = new JSONArray();
        try {
            array.put(0, "download");
            array.put(1, per.toString());
            handler.obtainMessage(MSG_PROG_INSHOW, array).sendToTarget();
        } catch (Exception ex) {
            Log.e(TAG, "array combine fail", ex);
        }
    }

    Runnable innerProcessor = new Runnable() {
        private int type = 0;//进程业务标识 1比较版本 2下载更新包

        @Override
        public void run() {
            //比较版本以及更新
            handler.obtainMessage(MSG_PROG_COMPAREVERSION).sendToTarget();
            compareVersion();
            //比较后发送消息给主进程
            handler.obtainMessage(MSG_PROG_GOPAGE).sendToTarget();
        }
    };

}
